//
//  BDVipPayView.m
//  BadBoy
//
//  Created by wen on 2017/5/3.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDVipPayView.h"

#import "Order.h"
#import "BDUserModel.h"
#import "AppDelegate.h"
#import "BDMalAddressTableViewCell.h"
#import "BDUserAddressModel.h"
#import "BDPayAddressChooseView.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
@interface BDVipPayView ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIView *bkView;

@property (nonatomic, assign) BDPayType type;
@property (nonatomic, assign) NSInteger productId;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *product;
@property (nonatomic, strong) NSString *price;

@property (nonatomic, strong) UITableView *addressTableView;

@property (nonatomic, assign) NSInteger payStyle;
@property (nonatomic, strong) NSArray *addressArray;

@property (nonatomic, strong) BDPayAddressChooseView *addressChooseView;
@property (nonatomic, strong) BDUserAddressModel *currentUserAddressModel;
@end

@implementation BDVipPayView

BOOL isStartPay;

+ (instancetype)showWithProductId:(NSInteger)productId type:(BDPayType)type title:(NSString *)title product:(NSString *)product price:(NSString *)price addressArray:(NSArray *)addressArray{
    if (isStartPay == YES) {
        return nil;
    }
    isStartPay = YES;
    BDVipPayView *chooseView = [[BDVipPayView alloc] init];
    chooseView.addressArray = addressArray;
    chooseView.type = type;
    chooseView.productId = productId;
    chooseView.title = title;
    chooseView.product = product;
    chooseView.price = price;
    chooseView.contentView.top = kBDScreenHeight;
    [[UIApplication sharedApplication].keyWindow addSubview:chooseView];
    
    for (BDUserAddressModel *address in chooseView.addressArray) {
        if (address.isDefault == YES) {
            chooseView.currentUserAddressModel = address;
            break;
        }
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        chooseView.contentView.bottom = kBDScreenHeight;
        chooseView.bkView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    } completion:^(BOOL finished) {
        
    }];
    
    chooseView.addressChooseView.left = kBDScreenWidth;
    chooseView.addressChooseView.bottom = kBDScreenHeight;
    
    __weak BDVipPayView *weakSelf = chooseView;
    chooseView.addressChooseView.finishBlock = ^(id result) {
        weakSelf.currentUserAddressModel = (BDUserAddressModel *)result;
        [weakSelf.addressTableView reloadData];
        [UIView animateWithDuration:0.3 animations:^{
            weakSelf.contentView.left = 0;
            weakSelf.addressChooseView.left = kBDScreenWidth;
        } completion:^(BOOL finished) {
            
        }];
    };
    
    return chooseView;
}

- (instancetype)init{
    CGRect frame = CGRectMake(0, 0, kBDScreenWidth, kBDScreenHeight);
    if (self = [super initWithFrame:frame]) {

    }
    return self;
}

- (void)hidden{
    [UIView animateWithDuration:0.3 animations:^{
        self.contentView.top = kBDScreenHeight;
        self.bkView.backgroundColor = [UIColor clearColor];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        isStartPay = NO;
    }];
}

- (void)tapGR{
    [self hidden];
}

- (UIView *)bkView{
    if (!_bkView) {
        self.bkView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, kBDScreenHeight)];
        _bkView.backgroundColor = [UIColor clearColor];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGR)];
        [_bkView addGestureRecognizer:tap];
        [self insertSubview:_bkView atIndex:0];
    }
    return _bkView;
}

- (UIView *)contentView{
    if (!_contentView) {
        self.contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, kBDScreenHeight / 2.0)];
        _contentView.backgroundColor = [UIColor whiteColor];
        
        UILabel *label = [[UILabel alloc] init];
        label.text = self.title;
        label.font = [UIFont systemFontOfSize:16];
        label.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
        [label sizeToFit];
        label.centerX = kBDScreenWidth / 2.0;
        label.height = 45;
        [_contentView addSubview:label];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
        line.backgroundColor = kBDColorGray;
        line.top = label.bottom;
        [_contentView addSubview:line];
        
        UILabel *label1 = [[UILabel alloc] init];
        label1.text = self.product;
        label1.font = [UIFont systemFontOfSize:14];
        label1.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
        [label1 sizeToFit];
        label1.top = line.bottom;
        label1.left = 20;
        label1.height = 45;
        [_contentView addSubview:label1];
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
        line1.backgroundColor = kBDColorGray;
        line1.top = label1.bottom;
        [_contentView addSubview:line1];
        
        UILabel *label2 = [[UILabel alloc] init];
        label2.text = ASLocalizedString(@"支付方式：");
        label2.font = [UIFont systemFontOfSize:14];
        label2.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
        [label2 sizeToFit];
        label2.top = line1.bottom;
        label2.left = 20;
        label2.height = 45;
        [_contentView addSubview:label2];
        
        NSArray *imageArray = @[@"zfb_icon",@"wx_icon"];
        NSArray *titleArray = @[ASLocalizedString(@"支付宝"), ASLocalizedString(@"微信支付")];
        CGFloat startRight = kBDScreenWidth - 15;
        for (int i = 0; i < 2; i++) {
            UIView *payStyleView = [[UIView alloc] initWithFrame:CGRectMake(0, label2.top, 0, 45)];
            
            UIImageView *pointImageView = [[UIImageView alloc] init];
            if (self.payStyle != i) {
                pointImageView.image = [UIImage imageNamed:@"queren_sel"];
            }else {
                pointImageView.image = [UIImage imageNamed:@"queren"];
            }
            pointImageView.size = CGSizeMake(20, 20);
            pointImageView.left = 0;
            pointImageView.centerY = payStyleView.height / 2.0;
            pointImageView.tag = 5555 + i;
            [payStyleView addSubview:pointImageView];
            
//            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
//            imageView.image = [UIImage imageNamed:imageArray[i]];
//            imageView.centerY = payStyleView.height / 2.0;
//            imageView.left = pointImageView.right + 2;
//            [payStyleView addSubview:imageView];
            
            UILabel *titleLabel = [[UILabel alloc] init];
            titleLabel.font = [UIFont systemFontOfSize:14];
            titleLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
            titleLabel.text = titleArray[i];
            [titleLabel sizeToFit];
            titleLabel.left = pointImageView.right + 5;
            titleLabel.centerY = pointImageView.centerY;
            [payStyleView addSubview:titleLabel];
            
            payStyleView.width = titleLabel.right;
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = payStyleView.bounds;
            [payStyleView addSubview:button];
            payStyleView.right = startRight;
            startRight = payStyleView.left - 25;
            [_contentView addSubview:payStyleView];
            
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if (i != self.payStyle) {
                    return;
                }
                UIImageView *imageView1 = [_contentView viewWithTag:5555];
                UIImageView *imageView2 = [_contentView viewWithTag:5556];
                self.payStyle = i == 0 ? 1 : 0;
                if (self.payStyle == 0) {
                    imageView2.image = [UIImage imageNamed:@"queren_sel"];
                    imageView1.image = [UIImage imageNamed:@"queren"];
                }else{
                    imageView1.image = [UIImage imageNamed:@"queren_sel"];
                    imageView2.image = [UIImage imageNamed:@"queren"];
                }
                
            }];
        }
        
        UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
        line2.backgroundColor = kBDColorGray;
        line2.top = label2.bottom;
        [_contentView addSubview:line2];
        
        CGFloat buuttonTop = line2.bottom + 10;
        
        if (self.addressArray.count) {
            [_contentView addSubview:self.addressTableView];
            self.addressTableView.top = buuttonTop;
            
            UIView *line5 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
            line5.backgroundColor = kBDColorGray;
            line5.top = self.addressTableView.bottom;
            [_contentView addSubview:line5];
            
            buuttonTop = line5.bottom;
        }
        
        UILabel *label3 = [[UILabel alloc] init];
        label3.text = ASLocalizedString(@"金额：");
        label3.font = [UIFont systemFontOfSize:14];
        label3.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
        [label3 sizeToFit];
        label3.top = buuttonTop;
        label3.left = 20;
        label3.height = 45;
        [_contentView addSubview:label3];
        
        UILabel *label4 = [[UILabel alloc] init];
        label4.text = self.price;
        label4.font = [UIFont systemFontOfSize:14];
        label4.textColor = [UIColor colorWithHexString:@"#ff8400"];
        [label4 sizeToFit];
        label4.top = buuttonTop;
        label4.right = self.width - 15;
        label4.height = 45;
        [_contentView addSubview:label4];
        
        UIView *line3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
        line3.backgroundColor = kBDColorGray;
        line3.top = label3.bottom;
        [_contentView addSubview:line3];
        
        
        UIButton *payButton = [UIButton buttonWithType:UIButtonTypeCustom];
        payButton.size = CGSizeMake(kBDScreenWidth - 20, 47);
        payButton.top = line3.bottom + 10;
        payButton.centerX = kBDScreenWidth / 2.0;
        [payButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [payButton setTitle:ASLocalizedString(@"支付购买")forState:UIControlStateNormal];
        payButton.titleLabel.font = [UIFont systemFontOfSize:18];
        payButton.layer.cornerRadius = 5;
        payButton.backgroundColor = [UIColor colorWithHexString:@"4d7aad"];
        [[payButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            // BDLog(ASLocalizedString(@"点击了购买按钮"));
            if (self.payStyle == 0) {
                [self wxPay];
            }else if (self.payStyle == 1) {
                [self aliPay];
            }
            
        }];
        [_contentView addSubview:payButton];
        _contentView.height = payButton.bottom + 10;
        
        [self addSubview:_contentView];
    }
    return _contentView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BDMalAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bdAddressCell"];
    if (cell == nil) {
        cell = [[BDMalAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"bdAddressCell"];
    }
    [cell configeWithModel:self.currentUserAddressModel];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [UIView animateWithDuration:0.3 animations:^{
        self.contentView.right = 0;
        self.addressChooseView.left = 0;
    } completion:^(BOOL finished) {
        
    }];
}

- (UITableView *)addressTableView{
    if (!_addressTableView) {
        self.addressTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 70)];
        _addressTableView.delegate = self;
        _addressTableView.dataSource = self;
        _addressTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _addressTableView;
}

- (BDPayAddressChooseView *)addressChooseView{
    if (!_addressChooseView) {
        self.addressChooseView = [[BDPayAddressChooseView alloc] initWithFrame:self.contentView.bounds addressArray:self.addressArray];
        [self addSubview:_addressChooseView];
    }
    return _addressChooseView;
}

- (void)aliPay{
    
    NSString *url = [NSString stringWithFormat:@"%@payment/ali/orderInfo", KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    NSDictionary *para = nil;
    if (self.currentUserAddressModel) {
        para = @{@"id":@(self.productId),
                 @"type":@(self.type),
                 @"address_id":@(self.currentUserAddressModel.address_id)};
    }else{
        para = @{@"id":@(self.productId),
                 @"type":@(self.type)};
    }
    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        NSString *appScheme = @"beBoyAliPay";
        [[AlipaySDK defaultService] payOrder:x[@"info"] fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            if (app.payResultBlock) {
                NSInteger stateCode = [resultDic[@"resultStatus"] integerValue];
                if (stateCode == 9000) {
                    app.payResultBlock(1);
                }
            }
        }];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"支付宝请求数据错误：%@"), error);
    }];
}

- (void)wxPay{
    NSString *url = [NSString stringWithFormat:@"%@payment/wechat/preOrder", KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    NSDictionary *para = nil;
    if (self.currentUserAddressModel) {
        para = @{@"id":@(self.productId),
                 @"type":@(self.type),
                 @"address_id":@(self.currentUserAddressModel.address_id)};
    }else{
        para = @{@"id":@(self.productId),
                 @"type":@(self.type)};
    }
    
    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        PayReq *request = [[PayReq alloc] init];
        request.openID = x[@"app_id"];
        request.partnerId = x[@"merchant_id"];
        request.prepayId = x[@"prepay_id"];
        request.package = @"Sign=WXPay";
        request.nonceStr= x[@"nonce_str"];
        request.timeStamp= (UInt32)[x[@"timestamp"] integerValue];
        request.sign= x[@"sign"];
        [WXApi sendReq:request];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"微信统一下单错误：%@"), error);
    }];
}

@end
